import { Button, NavBar, Form, Input, List, Toast } from 'antd-mobile'
import { useDispatch } from 'react-redux'
// import { login } from '@/store/actions/login'
import { login, getCode } from '@/store/actions/login'
import styles from './index.module.scss'
import { LoginForm } from '@/types/data'
import { useHistory } from 'react-router-dom'
import { AxiosError } from 'axios'
import { useRef, useState } from 'react'
import { InputRef } from 'antd-mobile/es/components/input'
import useCountDown from '@/hooks/useCountDown'

const Login = () => {
  const { count, start } = useCountDown(10, () => { setSendable(true) })
  // eslint-disable-next-line no-unused-vars
  const [sendable, setSendable] = useState(true)
  const inputRef = useRef<InputRef>(null)
  const [form] = Form.useForm()
  const dispatch = useDispatch()
  const history = useHistory<{from: string} | undefined>()
  console.log(history.location)
  // 用户登录
  const onFinish = async (values: LoginForm) => {
    try {
      await dispatch(login(values))
      Toast.show({
        icon: 'success',
        content: '登录成功'
      })

      const path = history.location.state?.from || '/'
      history.replace(path)
    } catch (e) {
      const error = e as AxiosError<{message:string}>
      const content = error.response?.data.message || '登录失败'
      Toast.show({
        icon: 'fail',
        content
      })
    }
  }

  // 用户点击发送验证码
  const onSendCode = async () => {
    // 1. 拿到手机号
    const mobile = form.getFieldValue('mobile')
    // 2. 校验
    const arr = form.getFieldError('mobile')
    // 没有写手机号  或者 手机号格式不对
    if (!mobile || arr.length > 0) {
      inputRef.current?.focus()
      return
    }

    try {
      if (!sendable) {
        return
      }
      // 请求开始，倒计时启动
      setSendable(false)
      start()
      // 手机号不为空，且通过校验，可以请求接口发验证码
      await dispatch(getCode(mobile))
      Toast.show({ icon: 'success', content: '验证码发送成功' })
    } catch (e) {
      const error = e as AxiosError<{message:string}>
      const content = error.response?.data.message || '发送失败'
      Toast.show({ icon: 'fail', content })
    }
  }
  return (
    <div className={styles.root}>
      <NavBar></NavBar>

      <div className="login-form">
        <h2 className="title">账号登录</h2>

        <Form
          form={form}
          onFinish={onFinish}>
          <Form.Item
            className="login-item"
            name="mobile"
            rules={[
              { required: true, message: '手机号不能为空' },
              { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不对' }]}
            >
            <Input placeholder="请输入手机号" ref={inputRef}/>
          </Form.Item>
          <List.Item
            className="login-code-extra"
            extra={<span onClick={ sendable ? onSendCode : undefined } className="code-extra">
              {sendable ? '发送验证码' : count + '秒之后获取' }
              </span>}
          >
            <Form.Item
              name="code"
              className="login-item"
              rules={[{ required: true, message: '请输入验证码' }]}>
              <Input placeholder="请输入验证码" autoComplete="off" />
            </Form.Item>
          </List.Item>

          <Form.Item noStyle>
            <Button
              block
              type="submit"
              color="primary"
              className="login-submit"
            >
              提交
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}
export default Login
